package com.suedawn.bookmanagesystem.controller;

import cn.hutool.core.bean.BeanUtil;
import com.suedawn.bookmanagesystem.dto.WarehouseDTO;
import com.suedawn.bookmanagesystem.dto.WarehouseQueryDTO;
import com.suedawn.bookmanagesystem.entity.Warehouse;
import com.suedawn.bookmanagesystem.service.WarehouseService;
import com.suedawn.bookmanagesystem.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/api/warehouse")
@Api(tags = "仓库管理接口")
@CrossOrigin(origins = "http://localhost:5174")
public class WarehouseController {
    @Autowired
    private WarehouseService warehouseService;

    @PostMapping("/add")
    @ApiOperation("添加仓库")
    public R addWarehouse(@RequestBody WarehouseDTO dto){
        Warehouse warehouse = BeanUtil.copyProperties(dto, Warehouse.class);
        // 设置最后更新时间为当前时间
        warehouse.setLastUpdate(new Date());
        // 设置删除标志为0（未删除）
        warehouse.setDeleted(0);
        boolean save = warehouseService.save(warehouse);
        return save ? R.ok("添加成功") : R.error("添加失败");
    }

    @DeleteMapping("/del")
    @ApiOperation("删除仓库")
    public R removeWarehouse(@RequestParam("id") Integer id){
        boolean removed = warehouseService.removeById(id);
        return removed ? R.ok("删除成功") : R.error("删除失败");
    }

    @GetMapping("/list")
    @ApiOperation("获取仓库列表")
    public R listWarehouse(WarehouseQueryDTO dto){
        return warehouseService.listWarehouse(dto);
    }

    @PutMapping("/update")
    @ApiOperation("更新仓库信息")
    public R updateWarehouse(@RequestBody Warehouse warehouse){
        // 更新最后修改时间
        warehouse.setLastUpdate(new Date());
        boolean updated = warehouseService.updateById(warehouse);
        return updated ? R.ok("更新成功") : R.error("更新失败");
    }

    @GetMapping("/detail")
    @ApiOperation("获取仓库详情")
    public R getWarehouseDetail(@RequestParam("id") Integer id){
        Warehouse warehouse = warehouseService.getById(id);
        return warehouse != null ? R.ok(warehouse) : R.error("仓库不存在");
    }
}
